//
//  HOFaultCategoryViewController.m
//  微度报修
//
//  Created by foguo-mac-1 on 6/15/16.
//  Copyright © 2016 WeiDu. All rights reserved.
//

#import "HOFaultCategoryViewController.h"
#import "HOConstants.h"
#import "HOStaticDataMgr.h"
#import "HOFaultCategoryEntity.h"
#import "HOUtils.h"
#import "HOEditView.h"

@interface HOFaultCategoryViewController ()<UISearchBarDelegate>
{
	UITableView *secondTableView;
	HOEditView *editView;
	HO_SEARCH_STATUS searchStatus;
}
@property(nonatomic, retain)UIFont *contentFont;
@property(nonatomic, retain)NSString *key;
@property(nonatomic, retain)NSMutableArray *categoryList;
//存放搜索结果的数组
@property(nonatomic,strong)NSMutableArray *resultArray;
@end

@implementation HOFaultCategoryViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view.
	self.resultArray = [NSMutableArray array];
	self.contentFont = [UIFont systemFontOfSize:13];
	[self initTableViewWithPullUp];
	[self initSubviews];
	if(self.isDeviceDepartment)
	{
		[self initSearchBar];
	}
}

- (void)initSearchBar
{
	UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0,
															 0,
															 self.view.frame.size.width,
															 44)]autorelease] ;
	[view setBackgroundColor:TEXT_COLOR_E3E3E3];
	UISearchBar *searchBar = [[[UISearchBar alloc]
							   initWithFrame:CGRectMake(0,
														0,
														self.view.frame.size.width,
														44)] autorelease];
	
	[searchBar setBackgroundImage:[HOUtils createImageWithColor:TEXT_COLOR_E3E3E3 forView:searchBar]
				   forBarPosition:0
					   barMetrics:UIBarMetricsDefault];

		searchBar.showsCancelButton = YES;
	searchBar.delegate = self;
	searchBar.placeholder = NSLocalizedString(@"输入关键字", @"输入关键字");
	searchBar.tintColor = MAIN_COLOR_NORMAL;
	searchBar.showsCancelButton = YES;
	searchBar.keyboardType = UIKeyboardTypeDefault;
	[searchBar setBackgroundColor:[UIColor clearColor]];
	[view addSubview:searchBar];
	[self.view addSubview:view];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
	NSLog(@"输入搜索内容完毕");
	searchStatus = HO_SEARCH_SEARCHED;
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar;                      // return NO to not become first responder
{
	if(searchStatus == HO_SEARCH_SEARCHING)
		return NO;                   // return NO to not become first responder
	return YES;

}

- (void)pullUpToRefresh
{
	HOFaultCategoryEntity *entity = [self.categoryList lastObject];
	if(entity)
	{
		[self gotoSearchKey:self.key withMaxId:entity.faultId];
	}
	else
	{
		[self gotoSearchKey:self.key withMaxId:1];
	}
}

- (void)pullDownToRefresh
{
	[self gotoSearchKey:self.key withMaxId:1];
}


//搜框中输入关键字的事件响应
//-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
//
//	searchStatus = HO_SEARCH_OPENED;
//	NSLog(@"输入的关键字是-------------------------%@---%lu",searchText,(unsigned long)searchText.length);
//	[searchBar resignFirstResponder];
//	//需要事先情况存放搜索结果的数组
//	[self.resultArray removeAllObjects];
//
////	[self showLoadingView:YES];
//	//加个多线程，否则数量量大的时候，有明显的卡顿现象
//	//这里最好放在数据库里面再进行搜索，效率会更快一些
//	dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
//	dispatch_async(globalQueue, ^{
//		if (searchText!=nil && searchText.length>0) {
//			searchStatus = HO_SEARCH_SEARCHING;
//			//遍历需要搜索的所有内容，其中self.dataArray为存放总数据的数组
//			for (HOFaultCategoryEntity *entity in self.categoryList) {
//				if ([entity.pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length >0 ) {
//					//把搜索结果存放self.resultArray数组
//					NSLog(@"entity.faultDetail--%@  输入的关键字是:%@",entity.faultDetail, searchText);
//					[self.resultArray addObject:entity];
//				}
//				if([self.resultArray count] > 0)
//				{
//					self.currentEntity = self.resultArray.firstObject;
//				}
//				else
//				{
//					self.currentEntity = nil;
//				}
//			}
//		}else{
//			searchStatus = HO_SEARCH_NORESULT;
//			self.currentEntity = nil;
////			self.resultArray = [NSMutableArray arrayWithArray:self.categoryList];
//		}
//		//回到主线程
//		dispatch_async(dispatch_get_main_queue(), ^{
//			searchStatus = HO_SEARCH_SEARCHED;
//			[self showLoadingView:NO];
//			[baseTableview reloadData];
//			[secondTableView reloadData];
//		});
//	});
//}

//取消的响应事件
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
	
	NSLog(@"取消搜索");
	searchStatus = HO_SEARCH_CLOSED;
	[searchBar setShowsCancelButton:NO animated:YES];
	[searchBar resignFirstResponder];
	[self gotoSearchKey:@"" withMaxId:1];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
	if(searchText.length == 0)
	{
		searchStatus = HO_SEARCH_CLOSED;
		[searchBar endEditing:YES];
		[self gotoSearchKey:@"" withMaxId:1];
	}
}

//键盘上搜索事件的响应
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
	
	NSLog(@"搜索");
	[searchBar setShowsCancelButton:NO animated:YES];
	[searchBar resignFirstResponder];
	NSString *key = [[searchBar text] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	self.key = key;
	[self.resultArray removeAllObjects];
	[self gotoSearchKey:key withMaxId:1];
}

////在搜索框中修改搜索内容时，自动触发下面的方法
//-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
//	return YES;
//}
//
//#pragma mark - -- UISearchBarDelegate impelemnt methods
//// called when keyboard search button pressed
//- (void)searchBarSearchButtonClicked:(UISearchBar *)aSearchBar
//{
//	NSString *key = [[aSearchBar text] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//	[self gotoSearchKey:key];
//
//}
//
//- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
//{
//	[self requestData];
//}

- (void)gotoSearchKey:(NSString *)key
{
//	if(key.length < 2)
//	{
//		[self popupHintView:@"请输入两字或者两字以上关键字搜索"];
//		return;
//	}
	[self gotoSearchKey:key withMaxId:1];
}

- (void)gotoSearchKey:(NSString *)key withMaxId:(int)maxId
{
	[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_GetFaultTypeList, kHO_FIELD_Keywords:[HOUtils getValideString:key],
								  kHO_FIELD_DepartmentId:[NSNumber numberWithInt:self.departmentId],
								  kHO_FIELD_MaxID:[NSNumber numberWithInt:maxId]}];
}


- (void)initSubviews
{
	[self.view setBackgroundColor:[UIColor whiteColor]];
	baseTableview.frame = CGRectMake(0,
									 44,
									 self.view.frame.size.width / 2,
									 [HOUtils getScreenSize].height - 49 - 20 - 44);
	
	secondTableView = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 22,
																   baseTableview.frame.origin.y,
																   self.view.frame.size.width / 2 + 22,
																   baseTableview.frame.size.height - 50 - 44)
												  style:UITableViewStyleGrouped];
	[secondTableView setBackgroundColor:MAIN_BG_COLOR];
	secondTableView.delaysContentTouches = NO;
	secondTableView.delegate = self;
	secondTableView.dataSource = self;
	secondTableView.sectionFooterHeight = 0;
	secondTableView.separatorColor = TEXT_GRAY_DARK_dbdbdb;
	[self.view addSubview:secondTableView];
}

- (void)initDataSource
{
}

- (void)requestData
{
	[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_GetFaultTypeList,
								  kHO_FIELD_DepartmentId:[NSNumber numberWithInt:self.departmentId],
								  kHO_FIELD_MaxID:@"1"
								  }];
}

- (void)viewWillAppear:(BOOL)animated
{
	self.tabBarController.tabBar.hidden = YES;
	[super viewWillAppear:animated];
	[self setNavigationItemTitle:NSLocalizedString(@"选择故障分类", @"选择故障分类")];
	baseTableview.frame = CGRectMake(0,
									 (self.isDeviceDepartment ? 44 : 0),
									 self.view.frame.size.width / 2,
									 [HOUtils getScreenSize].height - 49 - 20 - (self.isDeviceDepartment ? 44 : 0));
	
	secondTableView.frame = CGRectMake(self.view.frame.size.width / 2,
																   baseTableview.frame.origin.y,
																   self.view.frame.size.width / 2,
									   baseTableview.frame.size.height - 50 - (self.isDeviceDepartment ? 44 : 0));
	
	self.categoryList = [[HOStaticDataMgr sharedInstance] getGategoryListWithDepartmentId:self.departmentId];
	if([self.categoryList count] == 0)
		[self requestData];
	else
		[self selectTheDefault];
}


- (NSInteger)getListCount
{
	if(searchStatus == HO_SEARCH_CLOSED)
	{
		
		return [self.categoryList count];
	}
	else
	{
		return 0;
	}
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}
#pragma mark - -- UITableViewDelegate/UITableViewDataResource implement methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//	HOFaultCategoryEntity *entity = nil;
//	if(indexPath.section == 0)
//	{
//
//		entity = [self.categoryList objectAtIndex:indexPath.row];
//	}
//	else
//	{
//		entity = [self.currentEntity.subTypes objectAtIndex:indexPath.row];
//	}
//
//	CGFloat width = tableView.frame.size.width / 2;
//	CGSize addressSize = [HOUtils findHeightForText:[HOUtils getValideString:entity.faultDetail] havingWidth:width andFont:self.contentFont];
//	CGFloat height = 20 + addressSize.height;
//	return MAX(44, height);
	return 50;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	NSInteger count = 0;
	if(searchStatus == HO_SEARCH_CLOSED)
	{
		
		count = [self.categoryList count];
	}
	else
	{
		count = [self.resultArray count];
	}
	
	if(count == 0)
	{
		return  0;
	}
	if(tableView == baseTableview)
	{
		return count;
	}
	else if(tableView == secondTableView)
	{
		if(self.currentEntity)
		{
			return [self.currentEntity.subTypes count];
		}
	}
	return 0;
}


- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return SECTION_PADDING / 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *AMBaseTableViewCellIdentifier = @"HOTableViewCell";
	HOTableViewCell *cell = (HOTableViewCell *)[tableView dequeueReusableCellWithIdentifier:AMBaseTableViewCellIdentifier];
	CGFloat cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
	if(cell == nil)
	{
		cell = [[[HOTableViewCell alloc]
				 initWithStyle:UITableViewCellStyleDefault
				 reuseIdentifier: AMBaseTableViewCellIdentifier] autorelease];
	}
	UILabel *lbl =(UILabel *)[cell viewWithTag:112];
	if(!lbl)
	{
		lbl = [[[UILabel alloc] initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
														 0,
														 tableView.frame.size.width - 30,
														 50)] autorelease];
		lbl.tag = 112;
		lbl.numberOfLines = 2;
//		lbl.layer.borderWidth = 1;
		lbl.font = [UIFont systemFontOfSize:14];
		lbl.textColor = TEXT_COLOR_181818;
		[cell.contentView addSubview:lbl];
	}
	UIImageView *imgView =(UIImageView *)[cell viewWithTag:113];
	if(!imgView)
	{
		imgView = [[[UIImageView alloc] initWithFrame:CGRectMake(tableView.frame.size.width - 12,
																 (cellHeight - 16) / 2,
																 9,
																 16)] autorelease];
		imgView.image = [UIImage imageNamed:@"ic_taizhuanyemian"];
		imgView.tag = 113;
		
		[cell.contentView addSubview:imgView];
	}
	cell.textLabel.font = [UIFont systemFontOfSize:14];
	cell.textLabel.textColor = TEXT_COLOR_181818;
	cell.selectionStyle = UITableViewCellSelectionStyleGray;
//	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	if(tableView == baseTableview)
	{
		HOFaultCategoryEntity *entity = nil;
		
		
		if(searchStatus == HO_SEARCH_CLOSED)
		{
			entity = [self.categoryList objectAtIndex:indexPath.row];
		}
		else
		{
			entity = [self.resultArray objectAtIndex:indexPath.row];
		}
		lbl.text =  entity.faultDetail;
	}
	else if(tableView == secondTableView)
	{
		HOFaultCategoryEntity *entity = [self.currentEntity.subTypes objectAtIndex:indexPath.row];
		lbl.text = entity.faultDetail;
	}
	[lbl sizeToFit];
	lbl.frame = CGRectMake(10,
						   (cellHeight - lbl.frame.size.height) / 2,
						   tableView.frame.size.width - 30,
						   lbl.frame.size.height);
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	//	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	if(tableView == baseTableview)
	{
		
		if(searchStatus == HO_SEARCH_CLOSED)
		{
			self.currentEntity = [self.categoryList objectAtIndex:indexPath.row];
		}
		else
		{
			self.currentEntity = [self.resultArray objectAtIndex:indexPath.row];
		}

		[secondTableView reloadData];
	}
	else if(tableView == secondTableView)
	{
		HOFaultCategoryEntity *entity = [self.currentEntity.subTypes objectAtIndex:indexPath.row];
		
		[self.delegate didSelectFault:self.currentEntity withSubEntity:entity];
		[self goBack];
	}
	
}


//-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//	
//	[tableView deselectRowAtIndexPath:indexPath animated:YES];
//	
//	UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//	
//	//把符合搜索条件的内容展示出来
//	JXSChannelModel *model = self.resultArray[indexPath.row];
//	cell.textLabel.text = model.ChannelName;
//}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (void)dealloc
{
	self.delegate = nil;
	[secondTableView release];
	[super dealloc];
}

#pragma mark
- (void)requestDidSuccessWithResponse:(HOBaseResponseEntity *)response
{
	if([response isEqualAction:kHO_ACTION_GetFaultTypeList])
	{
		if(![response.dataNode isKindOfClass:[NSArray class]])
		{
			return;
		}
		        NSData *data = [NSJSONSerialization dataWithJSONObject:response.dataNode options:NSJSONWritingPrettyPrinted error:nil];
		        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
		        NSLog(@"getFaultTypeList \n %@",str);
		NSArray *array = response.dataNode;
		[self.resultArray removeAllObjects];
		for(int i = 0; i < [array count]; i ++)
		{
			NSDictionary *subDic = [array objectAtIndex:i];
			
			int subFaultId = [[subDic objectForKey:kHO_FIELD_FaultId] intValue];
			HOFaultCategoryEntity *entity = [[HOStaticDataMgr sharedInstance] getFaultCategoryEntityWithId:subFaultId];
			[entity parseDic:subDic];
			entity.index = i;
			if(searchStatus == HO_SEARCH_CLOSED)
			{
				if(![self.categoryList containsObject:entity])
				{
					[self.categoryList addObject:entity];
				}
			}
			else
			{
				
				if(![self.resultArray containsObject:entity])
				{
					[self.resultArray addObject:entity];
				}
			}
		}
		
		[self selectTheDefault];
	}
}
- (void)selectTheDefault
{
	[self doneLoadingTableViewRefresh];
	if(searchStatus != HO_SEARCH_CLOSED)
	{
		if([self.resultArray count] == 0)
			return;
		//搜索模式
		self.currentEntity = [self.resultArray firstObject];
	}
	else
	{
		if([self.categoryList count] == 0)
			return;
		//费搜索模式
		if(self.currentEntity == nil || ![self.categoryList containsObject:self.currentEntity])
		{
			self.currentEntity = [self.categoryList firstObject];
		}
	}
	
	
	if(self.currentEntity.index < [self.categoryList count])
	{
		[baseTableview selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.currentEntity.index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
		[baseTableview scrollsToTop];
	}
	NSArray *secondAreaList = self.currentEntity.subTypes;
	if([secondAreaList count] == 0)
		return;
	
	[secondTableView reloadData];
	
	if(self.subEntity == nil)
		self.subEntity = [secondAreaList firstObject];
	if(self.subEntity.index < [secondAreaList count])
	{
		[secondTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.subEntity.index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
		[secondTableView scrollsToTop];
	}
	
}

@end
